<?php
/**
  * wechat php test
  */

//define your token
define("TOKEN", "weixin");
$wechatObj = new wechatCallbackapiTest();
//验证服务器和公众平台是否连接成功
//在服务器和公众平台验证成功之后，把$wechatObj->valid()注释掉
// $wechatObj->valid();
echo $wechatObj->responseMsg();

class wechatCallbackapiTest
{
	public function valid()
    {
        $echoStr = $_GET["echostr"];

        //valid signature , option
        if($this->checkSignature()){
        	echo $echoStr;
        	exit;
        }
    }
    //输出公众平台返回给用户的信息
    public function responseMsg()
    {
		//get post data, May be due to the different environments
        //相当于$_POST
		$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];

      	//extract post data
		if (!empty($postStr)){
                /* libxml_disable_entity_loader is to prevent XML eXternal Entity Injection,
                   the best way is to check the validity of xml by yourself */
                //只解析XML数据的主体部分，防止xxe攻击
                libxml_disable_entity_loader(true);
                //解析XML数据
              	$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
                //获取手机用户的OPenID
                $fromUsername = $postObj->FromUserName;
                //开发者微信号
                $toUsername = $postObj->ToUserName;
                //发送文本信息的关键字
                $keyword = trim($postObj->Content);
                //发送消息的类型
                $type = $postObj->MsgType;

                $time = time();
                //发送文本信息的字符串模板
                $textTpl = "<xml>
							<ToUserName><![CDATA[%s]]></ToUserName>
							<FromUserName><![CDATA[%s]]></FromUserName>
							<CreateTime>%s</CreateTime>
							<MsgType><![CDATA[%s]]></MsgType>
							<Content><![CDATA[%s]]></Content>
							<FuncFlag>0</FuncFlag>
							</xml>";
                //音乐消息的模板
                $musicTpl = "<xml>
                            <ToUserName><![CDATA[%s]]></ToUserName>
                            <FromUserName><![CDATA[%s]]></FromUserName>
                            <CreateTime>%s</CreateTime>
                            <MsgType><![CDATA[%s]]></MsgType>
                            <Music>
                            <Title><![CDATA[%s]]></Title>
                            <Description><![CDATA[%s]]></Description>
                            <MusicUrl><![CDATA[%s]]></MusicUrl>
                            <HQMusicUrl><![CDATA[%s]]></HQMusicUrl>
                            
                            </Music>
                            </xml>";
                //发送图文消息
                $newsTpl="<xml>
                            <ToUserName><![CDATA[%s]]></ToUserName>
                            <FromUserName><![CDATA[%s]]></FromUserName>
                            <CreateTime>%s</CreateTime>
                            <MsgType><![CDATA[%s]]></MsgType>
                            <ArticleCount>%s</ArticleCount>
                            <Articles>
                            %s
                            </Articles>
                            </xml> ";                           
                if($type == 'text'){
                    if(!empty( $keyword ))
                    {
                        // if($keyword == '音乐'){
                        //     $msgType = "music";
                        //     $title   = "See You Again";
                        //     $description='速度与激情7 原声大碟';
                        //     $music_url='http://www.yyzljg.com/wechat/music.mp3';
                        //     $high_url='http://www.yyzljg.com/wechat/music.mp3';
                        //     //格式化字符串
                        //     $resultStr = sprintf($musicTpl, $fromUsername, $toUsername, $time, $msgType,$title,$description,$music_url,$high_url);
                        //     echo $resultStr;
                        // }
                        if($keyword=='音乐'){
                                $msgType='music';
                                $title='冰雪奇缘主题曲';
                                $description='原声大碟';
                                $music_url='http://www.yyzljg.com/wechat/music.mp3';
                                $high_url='http://www.yyzljg.com/wechat/music.mp3';
                                //格式化字符串
                                $resultStr = sprintf($musicTpl, $fromUsername, $toUsername, $time, $msgType,$title,$description,$music_url,$high_url);
                                echo $resultStr;
                        }
                        if($keyword == '单图文'){
                            $msgType='news';
                            $counts=1;
                            $contentStr="<item>
                            <Title><![CDATA[大家一起学习微信开发]]></Title>
                            <Description><![CDATA[愿每天的你都是开心的！]]></Description>
                            <PicUrl><![CDATA[http://ibeliveone.applinzi.com/1.jpg]]></PicUrl>
                            <Url><![CDATA[http://ibeliveone.applinzi.com/1.jpg]]></Url>
                            </item>";

                            //格式化字符串
                            $resultStr = sprintf($newsTpl, $fromUsername, $toUsername, $time, $msgType,$counts,$contentStr);
                            echo $resultStr;
                        }
                        if($keyword == '多图文'){
                            $msgType='news';
                            $counts=4;
                            $contentStr='';
                            for($i=1;$i<=4;$i++){
                                $contentStr.="<item>
                                <Title><![CDATA[大家一起学习微信开发]]></Title>
                                <Description><![CDATA[愿每天的你都是开心的！]]></Description>
                                <PicUrl><![CDATA[http://ibeliveone.applinzi.com/{$i}.jpg]]></PicUrl>
                                <Url><![CDATA[http://ibeliveone.applinzi.com/{$i}.jpg]]></Url>
                                </item>";
                            }
                            //格式化字符串
                            $resultStr = sprintf($newsTpl, $fromUsername, $toUsername, $time, $msgType,$counts,$contentStr);
                            echo $resultStr;
                        } 
                        
                        //定义发送消息的类型
                        $msgType = "text";
                        //公众平台发送给用户的信息
                        $contentStr = "欢迎关注我的微信公众平台！";
                        //格式化字符串 
                        $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                        echo $resultStr;die;               
                    
                    
                    }else{
                        echo "Input something...";
                    }
                }elseif($type == 'image'){
                    //定义发送消息的类型
                    $msgType = "text";
                    //公众平台发送给用户的信息
                    $contentStr = "客官，您发送的美女好漂亮啊！";
                    //格式化字符串 
                    $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                    echo $resultStr; 
                    die;  
                }elseif($type == 'voice'){
                    //定义发送消息的类型
                    $msgType = "text";
                    //公众平台发送给用户的信息
                    $contentStr = "客官，您的声音好动听啊！";
                    //格式化字符串 
                    $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                    echo $resultStr;
                    die;
                }elseif($type == 'video'){
                    //定义发送消息的类型
                    $msgType = "text";
                    //公众平台发送给用户的信息
                    $contentStr = "客官，您分享的片片不是高清滴呦！";
                    //格式化字符串 
                    $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                    echo $resultStr;
                    die;
                }else{
                    //定义发送消息的类型
                    $msgType = "text";
                    //公众平台发送给用户的信息
                    $contentStr = "客官，我书读的少，不知道你想要什么服务，回复关键字有惊喜：'音乐'，'单图文'，'多图文'";
                    //格式化字符串 
                    $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                    echo $resultStr;
                    die;
                }                      
				

        }else {
        	echo "客官，我书读的少，不知道你想要什么服务，回复关键字有惊喜：'音乐'，'单图文'，'多图文'";
        	exit;
        }
    }
		
	private function checkSignature()
	{
        // you must define TOKEN by yourself
        if (!defined("TOKEN")) {
            throw new Exception('TOKEN is not defined!');
        }
        
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
        		
		$token = TOKEN;
		$tmpArr = array($token, $timestamp, $nonce);
        // use SORT_STRING rule
		sort($tmpArr, SORT_STRING);
		$tmpStr = implode( $tmpArr );
		$tmpStr = sha1( $tmpStr );
		
		if( $tmpStr == $signature ){
			return true;
		}else{
			return false;
		}
	}
}

?>